<template>
  <div class="container">
    <div class="flex">
      <el-button type="primary" @click="save" :loading="btn_loading"
        >保存</el-button
      >
      <el-button
        type="primary"
        @click=";(show_preview_box = true), (show_preview_type = 1)"
        >表单预览</el-button
      >
      <el-button
        type="primary"
        @click=";(show_preview_box = true), (show_preview_type = 2)"
        >列表预览</el-button
      >
      <el-button @click="router.back()">返回列表</el-button>
    </div>
    <div class="flex_js m_top10" style="height: calc(100% - 40px)">
      <div class="left">
        <div class="fs_16 fw m_bottom10">表单名称：{{ form_name }}</div>
        <div class="fs_16 fw m_bottom10">
          表单ID：{{ form_list[form_index].id }}
        </div>

        <el-collapse v-model="left_active" accordion>
          <el-collapse-item title="表单步骤" name="1">
            <leftName :form_list="form_list"></leftName>
          </el-collapse-item>
          <el-collapse-item title="表单布局" name="2">
            <div class="list_item_box">
              <div @click="add_base_box(form_list[form_index])">基础布局框</div>
              <div
                @click="
                  form_list[form_index].layout_list.push({
                    type: 'divider',
                    isShow: true,
                  })
                "
              >
                分割线
              </div>
              <!-- <div @click="
                  form_attr.layout_list.push({
                    type: '',
                    isShow: true,
                  })
                ">富文本编辑器</div> -->
            </div>
          </el-collapse-item>
          <el-collapse-item title="表单控件" name="3">
            <div class="list_item_box" @click="selectLeftItem">
              <div
                v-for="item in left_list"
                :key="item.name"
                v-bind:data-item="JSON.stringify(item)"
                :class="
                  select_left_item?.item_type + select_left_item?.type ==
                  item.item_type + item.type
                    ? 'left_item_select'
                    : ''
                "
              >
                {{ item.name }}
              </div>
            </div>
            <p style="color: #ccc; font-size: 12px">
              用法：点击-移动至单元格-再次点击
            </p>
          </el-collapse-item>
        </el-collapse>
      </div>
      <div
        class="main"
        @mousemove="onMousemove"
        @click="closeMousedownBxo($event)"
      >
        <div
          class="delete_area"
          v-if="showMousedownBox"
          @click=";(select_left_item = {}), (showMousedownBox = false)"
        >
          <svgBtn style="font-size: 23px" color="#999" icon="shanchu"></svgBtn>
        </div>
        <div class="delete_area" v-if="!showMousedownBox && position != ''">
          <el-button
            :disabled="position.split('_')[2] == '0'"
            @click="move_cell(1)"
          >
            前移 </el-button
          ><el-button
            :disabled="
              parseInt(position.split('_')[2]) + 1 >=
              form_list[form_index].layout_list[position.split('_')[1]].cells
            "
            @click="move_cell(2)"
          >
            后移
          </el-button>
          <span class="m_0_10"
            >移动至
            <el-input
              @blur="move_cell(3)"
              v-model="item_in_layout_index"
              style="width: 60px; text-align: center"
            ></el-input>
            格
          </span>
          <el-button @click="delete_cell(1)" v-if="select_base_item_right.code">
            清除控件
          </el-button>
          <el-button @click="delete_cell(2)"> 删除单元格 </el-button>
        </div>
        <div>
          <div class="flex_cc">
            <div
              v-for="(ii, indexii) in form_list"
              :key="indexii"
              class="fs_24 fw tc"
            >
              <span
                class="cp"
                :class="form_index == indexii ? 'c_3580eb' : ''"
                @click=";(form_index = indexii), (layout_list_key += 1)"
              >
                {{ ii.name }}</span
              >
              <span v-if="indexii != form_list.length - 1">--></span>
            </div>
          </div>
          <div>
            <div class="m_top10">
              <div
                v-for="(item, index) in form_list[form_index].layout_list"
                :key="layout_list_key"
              >
                <div
                  v-if="item.type == 'base_layout'"
                  class="base_layout_box"
                  v-masonry
                  fit-width="true"
                  transition-duration="0.3s"
                  item-selector=".base_layout_item"
                  origin-left="true"
                >
                  <!--  隐藏 流式布局第一行作为基准行不可修改  从第二行开始可以编辑单元格  -->
                  <div
                    v-masonry-tile
                    class="base_layout_item"
                    v-for="ii in item.cols"
                    :style="{ width: 100 / item.cols + '%' }"
                  ></div>
                  <div
                    v-masonry-tile
                    v-for="(item1, index1) in item.children_list"
                    :style="{
                      width: (item1.cols / item.cols) * 100 + '%',
                      height: item1.rows * 50 + 'px !important',
                    }"
                    :class="item.border ? 'base_layout_item_border' : ''"
                    class="base_layout_item"
                    @mouseover="fill_item_index = index + '_' + index1"
                    @mouseleave="fill_item_index = ''"
                    @click="click_base_item(index, index1)"
                  >
                    <div
                      style="
                        height: 100%;
                        width: 100%;
                        padding: 5px;
                        box-sizing: border-box;
                      "
                      class="flex_cc"
                      :class="
                        position == form_index + '_' + index + '_' + index1
                          ? 'select_base_item_index_border'
                          : ''
                      "
                      v-bind:data-itemindex="index1"
                      v-bind:data-boxindex="index"
                      v-if="
                        !item1.condition_show ||
                        (item1.condition_show && validata_condition(item1))
                      "
                    >
                      <div
                        style="width: 140px; flex-shrink: 0; text-align: right"
                      >
                        <span style="color: #ff0000" v-if="item1.is_required"
                          >*</span
                        >
                        {{ item1?.name ? item1?.name + '：' : '' }}
                      </div>
                      <div
                        class="selector_box"
                        :style="{
                          width: item1.item_type == 'textarea' ? '100%' : '',
                        }"
                      >
                        <selector
                          :item1="item1"
                          :selector_type="'main'"
                        ></selector>
                      </div>
                    </div>
                  </div>
                </div>
                <div v-if="item.type == 'divider'">
                  <el-divider
                    style="margin: 10px 0"
                    v-show="item.isShow"
                  ></el-divider>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="right">
        <div class="right_top">
          <div
            :class="rightActiveIndex == 1 ? 'rightActive' : ''"
            @click="rightActiveIndex = 1"
          >
            表单属性
          </div>
          <div
            :class="rightActiveIndex == 2 ? 'rightActive' : ''"
            @click="
              select_base_item_right == ''
                ? ElMessage.warning('请选择单元格')
                : (rightActiveIndex = 2)
            "
          >
            控件属性
          </div>
        </div>
        <div v-if="rightActiveIndex == 1">
          <div class="title m_top20">基本信息</div>
          <el-form label-width="80px">
            <el-form-item label="步骤名称">
              <el-input
                v-model="form_list[form_index].name"
                @change="change_form_index_name"
              ></el-input>
            </el-form-item>
            <!-- <el-form-item label="表单id">
              <el-input v-model="form_list[form_index].id" disabled></el-input
            ></el-form-item> -->
          </el-form>
          <div class="title m_top10 m_bottom10">权限配置</div>
          <el-checkbox
            v-for="(item, index) in right_list"
            :key="item.id"
            v-model="item.checked"
            :checked="item.checked"
            @change="(e) => change_right_list(e, index)"
          >
            <el-tooltip
              :content="'代号：' + item.right_code"
              placement="bottom"
            >
              {{ item.name }}
            </el-tooltip>
          </el-checkbox>
          <div>
            <el-button
              @click="
                ;(show_add_right_box = true), (show_add_right_box_type = 1)
              "
              type="primary"
              size="small"
            >
              增加按钮
            </el-button>
            <el-button
              v-if="right_list.length > 4"
              @click="
                ;(show_add_right_box = true),
                  (show_add_right_box_type = 2),
                  (add_right_form_data = right_list[4])
              "
              type="primary"
              size="small"
            >
              编辑按钮
            </el-button>
            <el-button @click="validata_edit_right" type="primary" size="small">
              按钮权限
            </el-button>
          </div>

          <div class="title m_top20">布局配置</div>
          <div class="m_top10">
            <div class="flex">
              <div style="width: 80px; flex-shrink: 0">表单宽度：</div>
              <el-input
                v-model="form_list[0].width"
                placeholder="请输入"
                type="number"
              >
                <template #append>%</template></el-input
              >
            </div>
            <el-divider style="margin: 5px 0"></el-divider>
            <div v-for="(item, index) in form_list[form_index].layout_list">
              <div v-if="item.type == 'base_layout'">
                <div class="flex_js">
                  <div>基础布局框</div>
                  <el-button size="small" @click="delete_base_layout(index)"
                    >删除</el-button
                  >
                </div>
                <el-form label-width="100px">
                  <el-form-item label="列数">
                    <el-select
                      style="width: 220px"
                      v-model="item.cols"
                      @change="
                        (e) => {
                          change_base_children_list(e, index, { type: 'rows' })
                        }
                      "
                    >
                      <el-option
                        v-for="item in 4"
                        :value="item"
                      ></el-option></el-select
                  ></el-form-item>
                  <el-form-item label="单元格数量">
                    <el-input-number
                      v-model="item.cells"
                      :min="1"
                      @change="
                        (e) => {
                          change_base_children_list(e, index, { type: 'cells' })
                        }
                      "
                    ></el-input-number>
                    <!-- <span class="fs_12"
                      >：减少单元格数量将不保存被减部分单元格内表单配置</span
                    > -->
                  </el-form-item>
                  <el-form-item label="边框">
                    <el-radio-group v-model="item.border">
                      <el-radio :label="true">显示</el-radio>
                      <el-radio :label="false">隐藏</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-form>
              </div>
              <div v-if="item.type == 'divider'">
                <div class="flex_js">
                  <div>分割线</div>
                  <el-button
                    size="small"
                    @click="form_list[form_index].layout_list.splice(index, 1)"
                    >删除</el-button
                  >
                </div>
                <el-radio-group v-model="item.isShow">
                  <el-radio :label="true">显示</el-radio>
                  <el-radio :label="false">隐藏</el-radio>
                </el-radio-group>
              </div>
              <el-divider style="margin: 5px 0"></el-divider>
            </div>
          </div>
        </div>
        <div v-if="rightActiveIndex == 2">
          <div class="m_top10" v-if="select_base_item_right != ''">
            <el-form label-width="90px" :model="select_base_item_right">
              <el-form-item label="字段名称" :rules="rules.name" prop="name">
                <el-input
                  v-model="select_base_item_right.name"
                  :disabled="select_base_item_right.code === undefined"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
              <el-form-item
                label="字段代号"
                :rules="right_rules.code"
                prop="type"
              >
                <el-input
                  v-model="select_base_item_right.code"
                  @blur="validata_code"
                  placeholder="请输入"
                  :disabled="select_base_item_right.code === undefined"
                  ref="codeInput"
                >
                  <template #append
                    ><div class="cp" @click="show_rule">建议</div></template
                  ></el-input
                >
              </el-form-item>
              <el-form-item label="作为表头">
                <el-radio-group
                  v-model="select_base_item_right.show_table"
                  :disabled="select_base_item_right.code === undefined"
                  ><el-radio :value="0" :label="false">否</el-radio>
                  <el-radio :value="1" :label="true">是</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="是否必填">
                <el-radio-group
                  @change="change_is_required"
                  v-model="select_base_item_right.is_required"
                  :disabled="select_base_item_right.code === undefined"
                  ><el-radio :value="0" :label="false">否</el-radio>
                  <el-radio :value="1" :label="true">是</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="是否只读">
                <div class="flex_js w_100">
                  <el-radio-group
                    v-model="select_base_item_right.disabled"
                    :disabled="select_base_item_right.code === undefined"
                    ><el-radio :value="0" :label="false">否</el-radio>
                    <el-radio :value="1" :label="true">是</el-radio>
                  </el-radio-group>
                  <el-button
                    type="primary"
                    size="small"
                    v-if="select_base_item_right.disabled"
                    @click="
                      ;(show_condition_setup_box = true),
                        (condition_setup_code = select_base_item_right.code),
                        (position = select_base_item_right.position)
                      show_condition_setup_box_type = 'readOnly'
                    "
                    >条件配置</el-button
                  >
                </div>
              </el-form-item>
              <el-form-item label="显示条件">
                <div class="flex_js w_100">
                  <el-radio-group
                    v-model="select_base_item_right.condition_show"
                    :disabled="select_base_item_right.code === undefined"
                  >
                    <el-radio :value="0" :label="false">无</el-radio
                    ><el-radio :value="1" :label="true">有</el-radio>
                  </el-radio-group>
                  <el-button
                    type="primary"
                    size="small"
                    v-if="select_base_item_right.condition_show"
                    @click="
                      ;(show_condition_setup_box = true),
                        (condition_setup_code = select_base_item_right.code)
                      position = select_base_item_right.position
                      show_condition_setup_box_type = 'display'
                    "
                    >条件配置</el-button
                  >
                </div>
              </el-form-item>
              <el-form-item
                label="是否多选"
                v-if="select_base_item_right.item_type == 'select'"
              >
                <el-radio-group
                  v-model="select_base_item_right.multiple"
                  @change="layout_list_key += 1"
                >
                  <el-radio :value="1" :label="true">是</el-radio
                  ><el-radio :value="0" :label="false">否</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item
                label="是否多选"
                v-if="select_base_item_right.item_type == 'tree'"
              >
                <el-radio-group
                  v-model="select_base_item_right.props.multiple"
                  @change="layout_list_key += 1"
                >
                  <el-radio :value="1" :label="true">是</el-radio
                  ><el-radio :value="0" :label="false">否</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item
                label="任一级可选"
                v-if="select_base_item_right.item_type == 'tree'"
              >
                <el-radio-group
                  v-model="select_base_item_right.props.checkStrictly"
                  @change="layout_list_key += 1"
                >
                  <el-radio :value="1" :label="true">是</el-radio
                  ><el-radio :value="0" :label="false">否</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item
                label="最大数量"
                v-if="
                  ['input', 'textarea'].includes(
                    select_base_item_right?.item_type
                  )
                "
              >
                <el-input
                  v-model="select_base_item_right.max_length"
                  type="number"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
              <el-form-item label="占用行数">
                <el-select
                  v-model="select_base_item_right.rows"
                  :disabled="select_base_item_right.code === undefined"
                  @change="layout_list_key += 1"
                >
                  <el-option
                    v-for="item in 6"
                    :value="item"
                    :label="item"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="占用列数">
                <el-select
                  v-model="select_base_item_right.cols"
                  :disabled="select_base_item_right.code === undefined"
                  @change="layout_list_key += 1"
                >
                  <el-option
                    v-for="item in form_list[form_index].layout_list[
                      position.split('_')[1]
                    ].cols"
                    :value="item"
                    :label="item"
                  ></el-option>
                </el-select>
              </el-form-item>
              <div
                v-if="
                  ['checkBox', 'radio', 'select', 'tree'].includes(
                    select_base_item_right?.item_type
                  )
                "
              >
                <div>选项列表</div>
                <el-table
                  :data="select_base_item_right.data"
                  class="m_top10 tc"
                  max-height="500px"
                  row-key="value"
                  default-expand-all
                >
                  <el-table-column label="名称" prop="label">
                    <template #default="scope: any">
                      <el-input
                        v-model="scope.row.label"
                        size="small"
                      ></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="值" prop="value" width="80px"
                    ><template #default="scope: any">
                      <el-input
                        v-model="scope.row.value"
                        :disabled="
                          select_base_item_right.value !== null &&
                          (Array.isArray(select_base_item_right.value)
                            ? select_base_item_right.value
                                .flat(Infinity)
                                .includes(scope.row.value)
                            : select_base_item_right.value.includes(
                                scope.row.value
                              ))
                        "
                        size="small"
                        @blur="validate_value(scope.$index)"
                      ></el-input> </template
                  ></el-table-column>
                  <el-table-column label="操作" width="96px">
                    <template #default="scope: any">
                      <el-dropdown style="width: 100%">
                        <div class="tc" style="width: 100%">
                          <el-button size="small">更多</el-button>
                        </div>
                        <template #dropdown>
                          <div>
                            <el-button
                              size="small"
                              @click="delete_option(scope.row.value)"
                              >删除</el-button
                            >
                          </div>
                          <div>
                            <el-button
                              size="small"
                              style="margin: 0"
                              v-if="!scope.row.disabled"
                              @click="put_status(scope.row.value)"
                              >禁用</el-button
                            >
                            <el-button
                              size="small"
                              style="margin: 0"
                              v-else
                              @click="put_status(scope.row.value)"
                              >启用</el-button
                            >
                          </div>

                          <div
                            v-if="
                              select_base_item_right.item_type == 'tree' &&
                              scope.row.children
                            "
                          >
                            <el-button
                              size="small"
                              style="margin: 0"
                              @click="add_child_option(scope.row.value)"
                              >加子项</el-button
                            >
                          </div>
                        </template>
                      </el-dropdown>
                    </template>
                  </el-table-column>
                </el-table>
                <div class="m_top10">
                  <el-button size="small" type="primary" @click="add_data_row"
                    >追加行</el-button
                  >
                </div>
              </div>
              <el-form-item
                label="刻度时长"
                v-if="select_base_item_right?.item_type == 'time'"
              >
                <el-select
                  v-model="select_base_item_right.step"
                  @change="
                    ;(select_base_item_right.startTime = ''),
                      (select_base_item_right.endTime = '')
                  "
                >
                  <el-option
                    v-for="item in time_list"
                    :key="item.value"
                    :value="item.value"
                    :label="item.label"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                label="区间选择"
                v-if="select_base_item_right?.item_type == 'time'"
              >
                <el-radio-group
                  v-model="select_base_item_right.is_time_between"
                  @change="select_base_item_right.endTime = ''"
                >
                  <el-radio :value="1" :label="true">是</el-radio
                  ><el-radio :value="0" :label="false">否</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item
                label="选择类型"
                v-if="select_base_item_right?.item_type == 'date'"
              >
                <el-select
                  v-model="select_base_item_right.date_type"
                  @change="select_base_item_right.value = ''"
                >
                  <el-option
                    v-for="item in date_list"
                    :key="item.value"
                    :value="item.value"
                    :label="item.label"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                label="文件数量"
                v-if="select_base_item_right?.item_type == 'upload'"
              >
                <el-select
                  v-model="select_base_item_right.limit"
                  @change="select_base_item_right.value = []"
                >
                  <el-option
                    v-for="item in 9"
                    :key="item"
                    :value="item"
                    :label="item"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                label="文件类型"
                v-if="select_base_item_right?.item_type == 'upload'"
              >
                <el-select
                  multiple
                  v-model="select_base_item_right.accept"
                  @change="select_base_item_right.value = []"
                >
                  <el-option-group
                    v-for="group in file_type_list"
                    :key="group.label"
                    :label="group.label"
                  >
                    <el-option
                      v-for="item in group.options"
                      :key="item.value"
                      :value="item.value"
                      :label="item.label"
                    />
                  </el-option-group>
                </el-select>
              </el-form-item>
              <el-form-item
                label="最小值"
                v-if="select_base_item_right?.item_type == 'input_number'"
              >
                <el-input-number v-model="select_base_item_right.min" :step="1">
                </el-input-number>
              </el-form-item>
              <el-form-item
                label="最大值"
                min="1"
                max="10000000"
                v-if="select_base_item_right?.item_type == 'input_number'"
              >
                <el-input-number v-model="select_base_item_right.max" :step="1">
                </el-input-number>
              </el-form-item>
              <el-form-item
                label="精度"
                v-if="
                  select_base_item_right?.item_type == 'input_number' &&
                  select_base_item_right.type == 'decimal'
                "
              >
                <el-select
                  placeholder="精确到小数点后几位"
                  clearable
                  v-model="select_base_item_right.precision"
                >
                  <el-option
                    v-for="item in 4"
                    :key="item"
                    :value="item"
                    :label="item"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </div>
    <div
      v-if="showMousedownBox"
      class="mousedownBox"
      @click="closeMousedownBxo"
      @mousemove="onMousemove"
      @contextmenu.prevent="closeMousedownBxo"
    >
      <div class="flex">
        <div>{{ select_left_item.name }}</div>
        <img
          src="@/assets/img/re_detail_1.png"
          style="width: 100px; height: 30px; margin-left: 10px"
          alt=""
        />
      </div>
    </div>
    <el-drawer
      v-model="show_add_right_box"
      direction="rtl"
      size="40%"
      :close-on-click-modal="false"
      destroy-on-close
      @close="resetForm(addrightform)"
    >
      <tempalte #title> <h4>权限</h4> </tempalte
      ><tempalte #default>
        <div v-if="show_add_right_box_type == 2">
          <div class="flex" style="overflow-x: auto">
            <div
              v-for="item in right_list"
              :key="item.id"
              class="update_right_list"
              @click="add_right_form_data = item"
              :class="item.id == add_right_form_data.id ? 'select' : ''"
            >
              {{ item.name }}
            </div>
          </div>

          <el-divider style="margin: 10px 0"></el-divider>
        </div>

        <el-form
          :model="add_right_form_data"
          ref="addrightform"
          :rules="right_rules"
          label-width="120px"
        >
          <el-form-item label="按钮名称" prop="name">
            <el-input
              :disabled="
                add_right_form_data.id != '' && add_right_form_data.id <= 4
              "
              v-model="add_right_form_data.name"
              placeholder="请输入"
            ></el-input> </el-form-item
          ><el-form-item label="按钮代号" prop="right_code">
            <el-input
              :disabled="
                add_right_form_data.id != '' && add_right_form_data.id <= 4
              "
              v-model="add_right_form_data.right_code"
              placeholder="请输入(不可重复)"
            ></el-input>
          </el-form-item>
          <el-form-item label="按钮操作类型">
            <el-select
              v-model="add_right_form_data.right_type"
              clearable
              :disabled="
                add_right_form_data.id != '' && add_right_form_data.id <= 4
              "
            >
              <el-option :value="1" label="表单操作"> </el-option>
              <el-option :value="2" label="弹窗确认"> </el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="对接接口地址">
            <el-input
              v-model="add_right_form_data.right_apiUrl"
              placeholder="请输入"
            >
            </el-input>
          </el-form-item> -->
          <el-form-item label="接口操作类型">
            <el-select
              v-model="add_right_form_data.right_method"
              :disabled="
                add_right_form_data.id != '' && add_right_form_data.id <= 4
              "
            >
              <el-option
                v-for="item in right_method_list"
                :key="item.value"
                :value="item.value"
                :label="item.label + '/' + item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <div class="tr m_top10">
            <el-button
              v-if="show_add_right_box_type == 2"
              @click="delete_right_list"
              >删除</el-button
            >
            <el-button @click="resetForm(addrightform)">取消</el-button>
            <el-button type="primary" @click="submit_right_list(addrightform)"
              >确定</el-button
            >
          </div>
        </el-form>

        <div class="p_10 m_top10 c_999" style="background-color: #f9f9f9">
          参数说明：操作类型与接口地址需对接后端开发人员，符合团队接口标准规范<br />
          例如本系统标椎：<br />新增(表单提交型)：post:服务地址+接口地址 -
          {body参数}
          <br />
          编辑(表单提交型)：put:服务地址+接口地址+/编辑id - {body参数}
          <br />
          查询(视具体而定)：get:服务地址+接口地址+/查询id
          <br />
          删除(弹窗确认型)：delete:服务地址+接口地址+/删除id
        </div>
      </tempalte>
    </el-drawer>
    <rightBox
      :show_edit_right_box="show_edit_right_box"
      :form_list="form_list"
      :right_list="right_list"
    ></rightBox>
    <conditionSetup
      :show_condition_setup_box="show_condition_setup_box"
      :form_list="form_list"
      :form_index="form_index"
      :condition_setup_code="condition_setup_code"
      :position="position"
      :show_condition_setup_box_type="show_condition_setup_box_type"
    ></conditionSetup>
    <preview
      :show_preview_box="show_preview_box"
      :show_preview_type="show_preview_type"
      :form_list="form_list"
      :form_width="form_list[0].width"
    ></preview>
  </div>
</template>

<script lang="ts" setup>
import { ref, onBeforeMount, computed, reactive, onUnmounted } from 'vue'
import svgBtn from '@/components/svg_button.vue'
import leftName from './components/leftName.vue'
import rightBox from './components/right.vue'
import selector from './components/selector.vue'
import conditionSetup from './components/conditionSetup.vue'
import preview from './components/preview.vue'
import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
import EventBus from '@/utils/EventBus'
import axios from '@/service/HttpRequest'
import serviceApi from '@/service/api'
import { FormInstance, ElMessageBox, ElMessage, FormRules } from 'element-plus'
const addrightform = ref<FormInstance>()
const right_rules = reactive<FormRules>({
  name: [{ required: true, message: '请输入按钮名称', trigger: 'blur' }],
  right_code: [{ required: true, message: '请输入按钮代号', trigger: 'blur' }],
  right_method: [
    { required: true, message: '请输入按钮操作类型', trigger: 'change' },
  ],
  code: [{ required: true, message: '请输入字段代号', trigger: 'blur' }],
})
const store = useStore()
const route = useRoute()
const router = useRouter()
const left_list = ref([
  {
    name: '单行文本输入框',
    type: 'varchar',
    item_type: 'input',
    code: 'input',
    value: '',
    pl: '请输入',
    is_required: false, // 必填
    disabled: false,
    max_length: '30',
    disabled_rule: [], // 禁用条件
    data: [],
    show_table: false, // 作为列表列展示
    condition_show: false, // 条件展示
    default: '',
  },
  {
    name: '多行文本输入框',
    type: 'varchar',
    item_type: 'textarea',
    code: 'textarea',
    value: '',
    pl: '请输入',
    max_length: '300',
    is_required: false,
    disabled: false,
    disabled_rule: [],
    data: [],
    show_table: false,
    condition_show: false, // 条件展示
    default: '',
  },
  {
    name: '数字输入框',
    type: 'double',
    item_type: 'input_number',
    code: 'input_number',
    value: '',
    min: 0,
    max: 10000000,
    precision: '2', // 精度  小数点几位
    pl: '请输入',
    is_required: false, // 必填
    disabled: false,
    max_length: '11',
    disabled_rule: [], // 禁用条件
    data: [],
    show_table: false, // 作为列表列展示
    condition_show: false, // 条件展示
    default: '',
  },
  {
    name: '金额输入框',
    type: 'decimal',
    item_type: 'input_number',
    code: 'input_number',
    value: '',
    min: 0,
    max: 10000000,
    precision: '2', // 精度  小数点几位
    pl: '请输入',
    is_required: false, // 必填
    disabled: false,
    max_length: '11',
    disabled_rule: [], // 禁用条件
    data: [],
    show_table: false, // 作为列表列展示
    condition_show: false, // 条件展示
    default: '',
  },
  {
    name: '普通选择框',
    type: 'varchar',
    item_type: 'select',
    code: 'select',
    value: '',
    pl: '请选择',
    data: [
      { value: '1', label: '选项1', disabled: false },
      { value: '2', label: '选项2', disabled: false },
    ],
    multiple: false,
    is_required: false,
    disabled: false,
    disabled_rule: [],
    show_table: false,
    condition_show: false, // 条件展示
    default: '',
    max_length: '1000',
  },
  {
    name: '单选按钮',
    type: 'varchar',
    item_type: 'radio',
    code: 'radio',
    value: '',
    pl: '',
    data: [
      { value: '1', label: '选项1', disabled: false },
      { value: '2', label: '选项2', disabled: false },
    ],
    is_required: false,
    disabled: false,
    disabled_rule: [],
    show_table: false,
    condition_show: false, // 条件展示
    default: '',
    max_length: '1000',
  },
  {
    name: '多选框',
    type: 'varchar',
    item_type: 'checkBox',
    code: 'checkBox',
    value: [],
    pl: '',
    data: [
      { value: '1', label: '选项1', disabled: false },
      { value: '2', label: '选项2', disabled: false },
    ],
    is_required: false,
    disabled: false,
    disabled_rule: [],
    show_table: false,
    condition_show: false, // 条件展示
    default: '',
    max_length: '1000',
  },
  {
    name: '时间选择器',
    type: 'text',
    item_type: 'time',
    code: 'time',
    is_time_between: false, // 是否为时间区间选择
    startTime: '',
    endTime: '',
    step: '00:15',
    pl: '请选择',
    is_required: false,
    disabled: false,
    disabled_rule: [],
    data: [],
    show_table: false,
    condition_show: false, // 条件展示
    default: '',
    max_length: '20',
  },
  {
    name: '日期选择器',
    type: 'bigint',
    item_type: 'date',
    code: 'date',
    value: '',
    date_type: 'date',
    max_length: '20',
    // year/month/date/dates/ week/daterange/ monthrange
    // 年 月 日 日多选 周 日区间 月区间
    startDate: '',
    endDate: '',
    pl: '请选择',
    is_required: false,
    disabled: false,
    disabled_rule: [],
    data: [],
    show_table: false,
    condition_show: false, // 条件展示
    default: '',
  },
  {
    name: '级联选择器',
    type: 'varchar',
    item_type: 'tree',
    code: 'tree',
    max_length: '1000',
    value: [],
    pl: '请选择',
    is_required: false,
    disabled: false,
    disabled_rule: [],
    props: { multiple: false, checkStrictly: false }, // 多选  任意一级可选
    data: [
      {
        value: '1',
        label: '选项1',
        disabled: false,
        children: [
          {
            value: '1-1',
            label: '选项1-1',
            disabled: false,
            children: [
              { value: '1-1-1', disabled: false, label: '选项1-1-1' },
              { value: '1-1-2', disabled: false, label: '选项1-1-2' },
            ],
          },
        ],
      },
    ],
    show_table: false,
    condition_show: false, // 条件展示
    default: '',
  },
  {
    name: '开关',
    type: 'char',
    item_type: 'switch',
    code: 'switch',
    value: true,
    pl: '',
    is_required: false,
    disabled: false,
    data: [],
    show_table: false,
    condition_show: false, // 条件展示
    default: '',
    max_length: '1',
  },
  {
    name: '上传',
    type: 'varchar',
    item_type: 'upload',
    code: 'upload',
    value: [], // 数据集
    width: '100', // 展示宽度
    height: '100', // 展示宽度
    limit: '1', // 多选
    uploadUrl: '', // 上传地址
    downloadUrl: '', // 下载地址
    is_required: false,
    disabled: false,
    disabled_rule: [],
    data: [],
    show_table: false,
    condition_show: false, // 条件展示
    default: '',
    max_length: '1000',
  },
])
const time_list = [
  { label: '1分钟', value: '00:01' },
  { label: '15分钟', value: '00:15' },
  { label: '30分钟', value: '00:30' },
  { label: '1小时', value: '01:00' },
  { label: '2小时', value: '02:00' },
]
const date_list = [
  { label: '日单选', value: 'date' },
  { label: '日 + 时间', value: 'datetime' },
  { label: '日多选', value: 'dates' },
  { label: '周', value: 'week' },
  { label: '月', value: 'month' },
  { label: '年', value: 'year' },
  { label: '日区间', value: 'daterange' },
  { label: '月区间', value: 'monthrange' },
]
const file_type_list = [
  // 图片
  {
    label: '图片类型',
    options: [
      { label: 'jpg', value: '.jpg' },
      { label: 'jpeg', value: '.jpeg' },
      { label: 'png', value: '.png' },
      { label: 'gif', value: '.gif' },
      { label: 'bmp', value: '.bmp' },
      { label: 'JPG', value: '.JPG' },
      { label: 'JPEG', value: '.JPEG' },
      { label: 'PBG', value: '.PBG' },
      { label: 'GIF', value: '.GIF' },
      { label: 'BMP', value: '.BMP' },
      { label: 'PDF', value: '.PDF' },
    ],
  },
  // 文件
  {
    label: '文件类型',
    options: [
      { label: 'pdf', value: '.pdf' },
      { label: 'doc', value: '.doc' },
      { label: 'docx', value: '.docx' },
      { label: 'xls', value: '.xls' },
      { label: 'xlsx', value: '.xlsx' },
      { label: 'txt', value: '.txt' },
      { label: 'rtf', value: '.rtf' },
      { label: 'ppt', value: '.ppt' },
      { label: 'pptx', value: '.pptx' },
      { label: 'dwg', value: '.dwg' },
      { label: 'rar', value: '.rar' },
      { label: 'zip', value: '.zip' },
      { label: '7z', value: '.7z' },
    ],
  },
]
const rules = {
  name: [{ required: true, message: '请输入字段名', trigger: 'blur' }],
  type: [{ required: true, message: '请输入字段id', trigger: 'blur' }],
}
const showMousedownBox = ref(false)
const left_active = ref('3')
const select_left_item = ref()
const x = ref()
const y = ref()
const x_position = computed(() => {
  return store.state.is_all_page ? 100 : store.state.isCollapse ? 200 : 300
})
const y_position = computed(() => {
  return store.state.is_all_page ? 80 : 130
})
const onMousemove = (e) => {
  x.value = e.x - x_position.value + 'px'
  y.value = e.y - y_position.value + 'px'
}
const selectLeftItem = (e) => {
  console.log(e)

  select_left_item.value = JSON.parse(e.target.dataset.item)
  x.value = e.x - x_position.value + 'px'
  y.value = e.y - y_position.value + 'px'
  showMousedownBox.value = true
}

// 选中框 单元格index 移动 用到
const item_in_layout_index = ref()
const select_base_item_right = ref<any>('')
// 关闭拖拽跟随 布局框点击事件
const closeMousedownBxo = (e) => {
  if (showMousedownBox.value) {
    if (fill_item_index.value == '') {
      ElMessage.warning('请放置于布局框内')
      return
    }
    form_list.value[form_index.value].layout_list.some((item, index) => {
      if (index == parseInt(fill_item_index.value.split('_')[0])) {
        item.children_list.some((item1, index1) => {
          if (index1 == parseInt(fill_item_index.value.split('_')[1])) {
            if (item.children_list[index1].name) {
              ElMessage.error('该位置已被占用')
            } else {
              select_left_item.value.code =
                select_left_item.value.item_type +
                form_index.value +
                '_' +
                fill_item_index.value
              item.children_list[index1] = Object.assign(
                item.children_list[index1],
                JSON.parse(JSON.stringify(select_left_item.value))
              )
            }
          }
          return index1 == parseInt(fill_item_index.value.split('_')[1])
        })
      }
      return index == parseInt(fill_item_index.value.split('_')[0])
    })
    console.log(form_list.value)
    select_left_item.value = {}
    showMousedownBox.value = false
  } else {
    console.log(e)
    if (e.target.dataset.boxindex && e.target.dataset.itemindex) {
      item_in_layout_index.value = parseInt(e.target.dataset.itemindex) + 1
      select_base_item_right.value =
        form_list.value[form_index.value].layout_list[
          e.target.dataset.boxindex
        ].children_list[e.target.dataset.itemindex]
      curr_codeInput_value.value = select_base_item_right.value.code
      // 位置 position
      position.value =
        form_index.value +
        '_' +
        e.target.dataset.boxindex +
        '_' +
        e.target.dataset.itemindex
      rightActiveIndex.value = 2

      console.log(position.value)
    }
  }
}

const condition_fun = (e) => {
  let children_list = []
  form_list.value[form_index.value].layout_list.forEach((item) => {
    children_list = children_list.concat(item.children_list)
  })
  console.log(e, children_list)
  let str = ''
  e.forEach((i, index) => {
    str +=
      i.code +
      '=' +
      i.value.toString() +
      (index != e.length - 1 ? i.relate : '')
  })
  let code_arr = []
  children_list.forEach((i) => {
    code_arr.push(i.code)
  })
  let value_arr = []
  children_list.forEach((i) => {
    value_arr.push(i.value + '')
  })
  console.log(code_arr, value_arr)
  let arr = str.split('||')
  return arr.some((i) => {
    return i.includes('&&')
      ? i.split('&&').every((ii) => {
          return (
            code_arr.includes(ii.split('=')[0]) &&
            value_arr.includes(ii.split('=')[1])
          )
        })
      : code_arr.includes(i.split('=')[0]) &&
          value_arr.includes(i.split('=')[1])
  })
}
// 显示条件校验 当前表单控件的值满足所有该控件的条件
const validata_condition = (e) => {
  let curr_condition_list = store.state.condition_setup_list.filter((item) => {
    return item.code == e.code
  })
  let curr_children_list = []
  form_list.value[form_index.value].layout_list.forEach((ii) => {
    curr_children_list = curr_children_list.concat(ii.children_list)
  })
  if (!curr_condition_list.length) return true
  let arr = curr_condition_list[0].condition_list.filter((item) => {
    return item.type == 'display'
  })
  return condition_fun(arr[0].children_list)
}

// 点击单元格
const click_base_item = (...e) => {
  setTimeout(() => {
    position.value = form_index.value + '_' + e[0] + '_' + e[1]
    item_in_layout_index.value = parseInt(e[1]) + 1
    select_base_item_right.value =
      form_list.value[form_index.value].layout_list[e[0]].children_list[e[1]]

    curr_codeInput_value.value = select_base_item_right.value.code
    console.log(select_base_item_right.value)
    rightActiveIndex.value = 2
  }, 100)
}
const fill_item_index = ref('')
const rightActiveIndex = ref(1)
const form_attr = ref({
  id: '1',
  name: '',
  width: '50',
  layout_list: [],
})
const right_list = ref([
  {
    name: '新增',
    checked: false,
    id: '1',
    right_code: 'add',
    right_method: 'post',
    right_type: 1,
  },
  {
    name: '删除',
    checked: false,
    id: '2',
    right_code: 'delete',
    right_method: 'delete',
    right_type: 2,
  },
  {
    name: '编辑',
    checked: false,
    id: '3',
    right_code: 'put',
    right_method: 'put',
    right_type: 1,
  },
  {
    name: '详情',
    checked: false,
    id: '4',
    right_code: 'info',
    right_method: 'post',
    right_type: 1,
  },
])
const layout_list_key = ref(0)
// 行列数更改 计算布局框
const change_base_children_list = (...e) => {
  let cells_num = form_list.value[form_index.value].layout_list[e[1]].cells
  let len =
    form_list.value[form_index.value].layout_list[e[1]].children_list.length
  if (cells_num < len) {
    let reduce_list =
      form_list.value[form_index.value].layout_list[e[1]].children_list.slice(
        cells_num
      )
    // 减少部分单元格
    console.log(len, cells_num, reduce_list)
    if (
      reduce_list.find((item) => {
        return item.code
      }) !== undefined
    ) {
      ElMessageBox.confirm(
        '删除的单元格中已配置表单控件，确认删除将不保留控件配置、权限配置、条件配置等',
        '',
        {
          cancelButtonText: '取消',
          confirmButtonText: '确定',
          closeOnClickModal: false,
          type: 'warning',
        }
      )
        .then(() => {
          delete_right_item(reduce_list)
          delete_condition_item(reduce_list)
          // 清除控件配置
          form_list.value[form_index.value].layout_list[
            e[1]
          ].children_list.length = cells_num
        })
        .catch(() => {
          form_list.value[form_index.value].layout_list[e[1]].cells +=
            len - cells_num
        })
    } else {
      form_list.value[form_index.value].layout_list[e[1]].children_list.length =
        cells_num
    }
  } else {
    let arr1 = []
    for (let i = 0; i < cells_num - len; i++) {
      arr1.push({
        cols: 1,
        rows: 1,
        position: form_index.value + '_' + e[1] + '_' + len + i,
      })
    }
    form_list.value[form_index.value].layout_list[e[1]].children_list =
      form_list.value[form_index.value].layout_list[e[1]].children_list.concat(
        arr1
      )
  }
  layout_list_key.value += 1
}
// 移动单元格
const move_cell = (e) => {
  let index_arr = JSON.parse(JSON.stringify(position.value.split('_')))
  let arr =
    form_list.value[form_index.value].layout_list[index_arr[1]].children_list
  if (
    item_in_layout_index.value > arr.length ||
    item_in_layout_index.value < 1
  ) {
    ElMessage.error('请在该布局框的单元格数量内移动！')
    setTimeout(() => {
      item_in_layout_index.value = parseInt(index_arr[2]) + 1
    }, 1000)
    return
  }
  item_in_layout_index.value =
    e == 1
      ? parseInt(index_arr[2]) - 1 + 1
      : e == 2
      ? parseInt(index_arr[2]) + 1 + 1
      : item_in_layout_index.value
  arr[item_in_layout_index.value - 1].position = arr[index_arr[2]].position
  // 位置互换
  arr.splice(
    item_in_layout_index.value - 1,
    1,
    ...arr.splice(
      parseInt(index_arr[2]),
      1,
      arr[item_in_layout_index.value - 1]
    )
  )
  // es6  不支持数组对象
  //   [arr[item_in_layout_index.value], arr[parseInt(index_arr[2])]] = [
  //     arr[parseInt(index_arr[2])],
  //     arr[item_in_layout_index.value],
  //   ];
  position.value =
    index_arr[0] + '_' + index_arr[1] + '_' + (item_in_layout_index.value - 1)
  arr[item_in_layout_index.value - 1].position = position.value
  console.log(arr[item_in_layout_index.value - 1], arr[index_arr[2]])
  // 更新权限 条件的position
  change_item_position(arr[item_in_layout_index.value - 1].code, position.value)
  change_item_position(arr[index_arr[2]].code, arr[index_arr[2]].position)
  layout_list_key.value += 1
}
// 删除单元格
const delete_cell = (e) => {
  let index_arr = position.value.split('_')
  let arr =
    form_list.value[index_arr[0]].layout_list[index_arr[1]].children_list
  console.log(arr[index_arr[2]])
  // 仅清除控件
  if (e == 1) {
    ElMessageBox.confirm('确定清除控件', '', {
      cancelButtonText: '取消',
      confirmButtonText: '确定',
      closeOnClickModal: false,
      type: 'warning',
    })
      .then(() => {
        delete_childrenList_item()
        layout_list_key.value += 1
      })
      .catch(() => {})
  } else {
    // 删除单元格
    // 判断空白单元格
    if (arr[index_arr[2]].code) {
      ElMessageBox.confirm(
        '删除该单元格将不保存该单元格中表单控件的配置，以及对应的权限配置、条件配置等',
        '',
        {
          cancelButtonText: '取消',
          confirmButtonText: '确定',
          closeOnClickModal: false,
          type: 'warning',
        }
      )
        .then(() => {
          // 清除权限  条件配置
          delete_right_item([arr[index_arr[2]]])
          delete_condition_item([arr[index_arr[2]]])
          // 删除位置后还有单元格 需更新其自身 以及 权限 条件中position
          arr.forEach((item, index) => {
            if (index > parseInt(index_arr[2])) {
              item.position = position_fun(item.position, '')
              if (item.code) {
                change_item_position(item.code, '')
              }
            }
          })
          arr.splice(parseInt(index_arr[2]), 1)
          form_list.value[index_arr[0]].layout_list[index_arr[1]].cells -= 1
          position.value = position_fun(position.value, '')
          click_base_item(
            position.value.split('_')[1],
            position.value.split('_')[2]
          )
          layout_list_key.value += 1
        })
        .catch(() => {})
    } else {
      console.log(arr, position.value)
      // 空白单元格后 有 配置控件的单元格 需更新其自身 以及 条件中position
      arr.forEach((item, index) => {
        if (index > parseInt(index_arr[2])) {
          item.position = position_fun(item.position, '')
          if (item.code) {
            change_item_position(item.code, '')
          }
        }
      })
      arr.splice(parseInt(index_arr[2]), 1)
      form_list.value[index_arr[0]].layout_list[index_arr[1]].cells -= 1
      position.value = position_fun(position.value, '')
      click_base_item(
        position.value.split('_')[1],
        position.value.split('_')[2]
      )
      layout_list_key.value += 1
    }
  }
}
const position_fun = (...position) => {
  console.log(position)
  if (position[1] != '') {
    return position[1]
  } else {
    return (
      position[0].split('_')[0] +
      '_' +
      position[0].split('_')[1] +
      '_' +
      (position[0].split('_')[2] - 1)
    )
  }
}
const change_item_position = (...e) => {
  console.log(e)
  let arr = store.state.condition_setup_list
    ? store.state.condition_setup_list
    : []
  // 更新自身条件以及其他关联自身的条件 的 position
  arr.forEach((item) => {
    if (item.code == e[0]) {
      item.position = position_fun(item.position, e[1])
    }
    item?.condition_list.forEach((item1) => {
      if (item1.code == e[0]) {
        item1.position = position_fun(item1.position, e[1])
      }
    })
  })
  store.commit('set_condition_setup_list', arr)
  // 更新权限相关 的 position
  let arr1 = store.state.customForm_right_list.length
    ? store.state.customForm_right_list
    : []
  arr1.forEach((item) => {
    item?.pre_right_data.forEach((item1) => {
      if (item1.code == e[0]) {
        item1.position = position_fun(item1.position, e[1])
      }
    })
    item?.operate_right_data.forEach((item1) => {
      if (item1.code == e[0]) {
        item1.position = position_fun(item1.position, e[1])
      }
    })
  })
  store.commit('set_customForm_right_list', arr1)
}
// 删除基础布局框
const delete_base_layout = (e) => {
  ElMessageBox.confirm(
    '删除基础布局框将不保存该部分中表单控件的配置，以及对应的控件配置、权限配置、条件配置等',
    '',
    {
      cancelButtonText: '取消',
      confirmButtonText: '确定',
      closeOnClickModal: false,
      type: 'warning',
    }
  )
    .then(() => {
      delete_right_item(
        form_list.value[form_index.value].layout_list[e].children_list
      )
      delete_condition_item(
        form_list.value[form_index.value].layout_list[e].children_list
      )
      // 清除布局配置
      form_list.value[form_index.value].layout_list.splice(e, 1)
    })
    .catch(() => {})
}
// 删除单元格内控件
const delete_childrenList_item = () => {
  let reduce_list = form_list.value[position.value.split('_')[0]].layout_list[
    position.value.split('_')[1]
  ].children_list.splice(position.value.split('_')[2], 1, {
    cols: 1,
    rows: 1,
    position: position.value,
  })
  delete_right_item(reduce_list)
  delete_condition_item(reduce_list)
  select_base_item_right.value = {
    cols: 1,
    rows: 1,
    position: position.value,
  }
  curr_codeInput_value.value = ''
  layout_list_key.value += 1
}
// 清除权限配置
const delete_right_item = (e) => {
  console.log(e)
  let arr = store.state.customForm_right_list.length
    ? store.state.customForm_right_list
    : []
  if (!arr.length) return
  arr.forEach((item) => {
    item.pre_right_data = item.pre_right_data.filter((item) => {
      return e.some((item1) => {
        return item1.code !== item.code
      })
    })
    item.operate_right_data = item.operate_right_data.filter((item) => {
      return e.some((item1) => {
        return item1.code !== item.code
      })
    })
  })
  store.commit('set_customForm_right_list', arr)
}
// 清除条件配置
const delete_condition_item = (e) => {
  console.log(e)
  let arr = store.state.condition_setup_list
    ? store.state.condition_setup_list
    : []
  if (!arr.length) return
  // 排除自身条件
  arr = arr.filter((item) => {
    return e.some((item1) => {
      return item1.code !== item.code
    })
  })
  // 排除其他关联自身的条件
  arr.forEach((item) => {
    item.condition_list = item.condition_list.filter((item) => {
      return e.some((item1) => {
        return item1.code !== item.code
      })
    })
  })
  store.commit('set_condition_setup_list', arr)
}
// 更改必填  更新权限字段
const change_is_required = (e) => {
  let arr = store.state.customForm_right_list.length
    ? store.state.customForm_right_list
    : []
  arr.forEach((item) => {
    item.operate_right_data.forEach((ii) => {
      console.log(ii.code)
      if (ii.code == curr_codeInput_value.value) {
        ii.is_required = e
      }
    })
  })
  store.commit('set_customForm_right_list', arr)
}
// 增加选项
const add_child_option = (e) => {
  console.log(e)
  select_base_item_right.value.data.forEach((item) => {
    if (item.value == e) {
      item.children.push({
        label: '选项名',
        value: random_value(),
        disabled: false,
        children: [],
      })
    }
    item.children.forEach((item1) => {
      if (item1.value == e) {
        item1.children.push({
          label: '选项名',
          value: random_value(),
          disabled: false,
        })
      }
    })
  })
}
// 增加选项
const add_data_row = () => {
  if (
    ['select', 'radio', 'checkBox'].includes(
      select_base_item_right.value.item_type
    )
  ) {
    select_base_item_right.value.data.push({
      label: '选项名',
      value: random_value(),
      disabled: false,
    })
  }
  if (select_base_item_right.value.item_type == 'tree') {
    select_base_item_right.value.data.push({
      label: '选项名',
      value: random_value(),
      disabled: false,
      children: [],
    })
  }
}
const put_status = (e) => {
  tree_forEach(select_base_item_right.value.data, e, 'status')
}
// 删除选项
const delete_option = (e) => {
  let arr = select_base_item_right.value.data
  if (select_base_item_right.value.item_type == 'tree') {
    tree_forEach(arr, e, 'del')
  } else {
    if (arr.length == 1) {
      ElMessage.warning('至少保留一条选项记录')
      return
    }
    select_base_item_right.value.value = ''
    let index = arr.findIndex((item) => item.value == e)
    arr.splice(index, 1)
    layout_list_key.value += 1
  }
}
const form_name = ref()
onBeforeMount(() => {
  get_form_info()
  if (route.query) {
    form_name.value = route.query.name
    form_list.value.push(
      init_form_attr({ name: route.query.name, id: route.query.id })
    )
  }
  EventBus.on('change_selector', () => {
    layout_list_key.value += 1
  })
  EventBus.on('change_form_name', (e) => {
    console.log(e)
    form_list.value = []
    form_index.value = 0
    layout_list_key.value += 1
    if (e.toString().length) {
      for (let i in e as any) {
        form_list.value.push(init_form_attr(e[i]))
      }
    } else {
      form_list.value.push(init_form_attr(''))
    }
    console.log(form_list.value)
  })
  EventBus.on('close_edit_right_box', () => {
    show_edit_right_box.value = false
  })
  EventBus.on('close_condition_setup_box', () => {
    show_condition_setup_box.value = false
    show_condition_setup_box_type.value = ''
    condition_setup_code.value = ''
  })
  EventBus.on('close_preview_box', () => {
    show_preview_box.value = false
  })
})
const get_form_info = () => {
  console.log(route.query)
  axios
    .request({
      url: serviceApi.form_configForm_info,
      method: 'get',
      params: { id: route.query.id },
    })
    .then((res) => {
      if (res.data !== null) {
        console.log(JSON.parse(res.data.rightJson))
        let arr = JSON.parse(res.data.rightJson)
        arr.forEach((i) => {
          let has_right = right_list.value.some((ii) => {
            if (ii.right_code == i.right_code) {
              ii.checked = true
            }
            return ii.right_code == i.right_code
          })
          if (!has_right && i.right_code != 'query') {
            right_list.value.push({
              name: i.right_name,
              right_code: i.right_code,
              checked: true,
              id: right_list.value.length + 1 + '',
              right_method: i.right_method,
              right_type: i.right_type ? 1 : i.right_type,
            })
          }
        })
        form_list.value = JSON.parse(res.data.formJson)
        form_index.value = 0
        store.commit(
          'set_condition_setup_list',
          JSON.parse(res.data.conditionJson)
        )
        store.commit(
          'set_customForm_right_list',
          JSON.parse(res.data.rightJson)
        )
      }
    })
    .catch((err) => {
      ElMessage.error(err)
    })
}
onUnmounted(() => {
  store.commit('clear_customForm_right_list')
  store.commit('clear_condition_setup_list')
})
const btn_loading = ref(false)
const save = () => {
  if (btn_loading.value) return
  btn_loading.value = true
  let arr = []
  form_list.value.forEach((item) => {
    item.layout_list.forEach((item1) => {
      item1.children_list.forEach((item2) => {
        if (item2.code) {
          arr.push(item2)
        }
      })
    })
  })
  let data = {
    basicId: form_list.value[0].id,
    controlJson: arr,
    rightJson: store.state.customForm_right_list.filter((i) => {
      return i.right_code != 'query'
    }),
    conditionJson: store.state.condition_setup_list,
    formJson: form_list.value,
    specialJson: [],
  }
  data.rightJson.push({
    right_name: '查询',
    right_code: 'query',
    right_method: 'post',
    right_type: 1,
    pre_right_data: [],
    operate_right_data: [],
  })
  axios
    .request({ url: serviceApi.form_configForm, method: 'post', data: data })
    .then((res) => {
      console.log(res)
      ElMessage.success('操作成功！')
      btn_loading.value = false
      router.back()
    })
    .catch((err) => {
      ElMessage.error(err)
      btn_loading.value = false
    })
}

const form_list = ref([])
const form_index = ref(0)
// 初始化 表单
const init_form_attr = (e) => {
  let OBJ = JSON.parse(JSON.stringify(form_attr.value))
  if (e != '') {
    OBJ.name = e.name
    OBJ.id = e.id
    OBJ.layout_list = []
  } else {
    OBJ.name = '表单名' + (form_list.value.length + 1)
    OBJ.id = form_list.value.length + 1 + ''
    OBJ.layout_list = []
  }
  return add_base_box(OBJ)
}
const add_base_box = (e) => {
  console.log(e)
  e.layout_list.push({
    type: 'base_layout',
    cells: 6,
    cols: 1,
    border: true,
    children_list: [],
  })

  // 位置 position
  for (let i = 0; i < e.layout_list.at(-1).cells; i++) {
    let obj = {
      cols: 1,
      rows: 1,
      position:
        form_list.value.length +
        '_' +
        (e.layout_list.length - 1) +
        '_' +
        e.layout_list.at(-1).children_list.length,
    }
    e.layout_list.at(-1).children_list.push(obj)
  }
  return e
}
const show_rule = () => {
  ElMessageBox.alert(
    '<p>字段代号命名 <b>不可重复</b> </br>命名规则：采用英文单词，多个单词时采用 驼峰法 或者 下划线链接，不计入空格 </p><p>如：用户：user；用户名：userName 或者 user_name</p>',
    '建议',
    {
      dangerouslyUseHTMLString: true,
    }
  )
}
// 生成 value不包含的 随机数
const random_value = () => {
  var random = Math.floor(Math.random() * 99) + 1
  let arr = select_base_item_right.value.data.flat(Infinity)
  let has_value = arr.some((item) => {
    return item.value == random
  })
  if (has_value) {
    random_value()
  } else {
    return random
  }
}
// 验证 选项值不重复
const validate_value = (e) => {
  console.log(e, select_base_item_right.value.data[e].value)
  if (select_base_item_right.value.data[e].value == '') {
    ElMessage.error('选项中值不能为空，已随机赋值')
    select_base_item_right.value.data[e].value = random_value()
    return
  }
  let arr = []
  select_base_item_right.value.data.forEach((item, index) => {
    if (index != e) {
      arr.push(item.value)
    }
  })
  console.log(arr)
  if (arr.includes(select_base_item_right.value.data[e].value)) {
    ElMessage.error('选项中值不能重复，已随机赋值')
    select_base_item_right.value.data[e].value = random_value()
  }
}
// 树形递归 选项列表删除 禁、启用操作 loop_index 循环层级
const tree_forEach = (arr, e, type, loop_index = 0) => {
  console.log(loop_index)
  arr.forEach((item, index) => {
    if (item.value == e) {
      if (type == 'del') {
        // 树形结构循环第一层为删除时
        if (arr.length == 1 && loop_index == 0) {
          ElMessage.warning('至少保留一条选项记录')
        } else {
          arr.splice(index, 1)
        }
      } else if (type == 'status') {
        item.disabled = !item.disabled
      }
    } else {
      if (item.children) {
        tree_forEach(item.children, e, type, (loop_index += 1))
      }
    }
  })
}
const change_right_list = (...e) => {
  console.log(e)
  if (!e[0]) {
    ElMessageBox.confirm('取消该权限将不保留该权限的相关配置', '', {
      cancelButtonText: '取消',
      confirmButtonText: '确定',
      closeOnClickModal: false,
      type: 'warning',
    })
      .then(() => {
        let arr = store.state.customForm_right_list
        arr = arr.filter((item) => {
          return item.right_code != right_list.value[e[1]].right_code
        })
        store.commit('set_customForm_right_list', arr)
      })
      .catch(() => {
        right_list.value[e[1]].checked = true
      })
  }
}
const validata_edit_right = () => {
  let has_checked = right_list.value.some((item) => {
    return item.checked
  })
  if (!has_checked) ElMessage.warning('请选择相关权限！')
  else {
    show_edit_right_box.value = true
  }
}
// 权限相关
const show_edit_right_box = ref(false)
const show_add_right_box = ref(false)
const show_add_right_box_type = ref<number>()
const add_right_form_data = ref<any>({
  name: '',
  right_code: '',
  right_method: '',
  checked: false,
  right_type: 1,
  id: '',
})
const right_method_list = [
  { label: '新增', value: 'post' },
  { label: '编辑', value: 'put' },
  { label: '查询', value: 'get' },
  { label: '删除', value: 'delate' },
]
// 增加 编辑权限
const submit_right_list = (formEl: FormInstance | undefined) => {
  formEl.validate((valid) => {
    if (valid) {
      let has_code = right_list.value.some((i) => {
        return (
          i.right_code == add_right_form_data.value.right_code &&
          i.id != add_right_form_data.value.id
        )
      })
      if (has_code) {
        ElMessage.error('按钮代号重复!')
        return
      }
      if (show_add_right_box_type.value == 1) {
        add_right_form_data.value.id =
          parseInt(right_list.value.at(-1).id) + 1 + ''
        right_list.value.push(
          JSON.parse(JSON.stringify(add_right_form_data.value))
        )
      } else {
        // 编辑是需同步更改权限配置相关参数
        let customForm_arr = store.state.customForm_right_list
        customForm_arr.some((i) => {
          if (i.id == add_right_form_data.value.id) {
            i.right_code = add_right_form_data.value.right_code
            i.right_name = add_right_form_data.value.name
            i.right_method = add_right_form_data.value.right_method
            i.right_type = add_right_form_data.value.right_type
          }
          return i.id == add_right_form_data.value.id
        })
        console.log(customForm_arr)
        store.commit('set_customForm_right_list', customForm_arr)
        right_list.value.forEach((i, index) => {
          if (i.id == add_right_form_data.value.id) {
            right_list.value[index] = add_right_form_data.value
          }
        })
      }
      console.log(add_right_form_data.value)
      resetForm(formEl)
    }
  })
}
// 删除按钮
const delete_right_list = () => {
  ElMessageBox.confirm('删除按钮将不保留其相关权限配置', '', {
    cancelButtonText: '取消',
    confirmButtonText: '确定',
    closeOnClickModal: false,
    type: 'warning',
  })
    .then(() => {
      // 过滤权限组
      let customForm_arr = store.state.customForm_right_list
      customForm_arr = customForm_arr.filter((i) => {
        return i.id != add_right_form_data.value.id
      })
      store.commit('set_customForm_right_list', customForm_arr)
      // 过滤按钮组
      right_list.value = right_list.value.filter((i) => {
        return i.id != add_right_form_data.value.id
      })
      if (right_list.value.length > 4) {
        add_right_form_data.value = right_list.value[4]
      } else {
        resetForm(addrightform.value)
      }
    })
    .catch(() => {})
}

// 展示条件配置
const show_condition_setup_box = ref(false)
const show_condition_setup_box_type = ref('') // 类型 readOnly 只读  display 展示  待后续扩展
const condition_setup_code = ref() // 当前项code
const position = ref('') // 当前项 位置

const codeInput = ref(null) // 字段code 元素
const curr_codeInput_value = ref('') // 获取当前code值 缓存  用于code修改后校验失败回填
// 字段code 唯一性验证  唯一：需同步至条件权限 重复：需将条件or权限的code回填
const validata_code = (e) => {
  console.log(curr_codeInput_value.value)
  let condition_arr = store.state.condition_setup_list
  let customForm_arr = store.state.customForm_right_list
  let data = e.target.value
  data = data.replace(/\s*/g, '') // 去除空格
  if (data == '') {
    ElMessageBox.confirm(
      '字段code不能为空，请重新赋值或直接删除（同时删除其条件以及权限的配置）',
      '',
      {
        cancelButtonText: '重新赋值',
        confirmButtonText: '直接删除',
        closeOnClickModal: false,
        type: 'error',
      }
    )
      .then(() => {
        delete_childrenList_item()
      })
      .catch(() => {
        select_base_item_right.value.code = curr_codeInput_value.value
        codeInput.value.focus()
      })
    return
  }
  let is_repeat = false
  let arr = position.value.split('_')
  form_list.value.forEach((item, index) => {
    item.layout_list.forEach((item1, index1) => {
      item1.children_list.forEach((item2, index2) => {
        if (
          item2.code == data &&
          (index != parseInt(arr[0]) ||
            index1 != parseInt(arr[1]) ||
            index2 != parseInt(arr[2]))
        ) {
          is_repeat = true
          ElMessage.error(
            `字段code与 ${item.name}-第${index1 + 1}个基础布局框中字段名为-${
              item2.name
            } 的code重复，请给予新值`
          )
        }
        // 重复 回填 之前的code
        if (is_repeat) {
          item2.code = curr_codeInput_value.value
        } else {
          curr_codeInput_value.value = item2.code
          // 没重复 将其对应的权限与条件code替换
          condition_arr.forEach((i) => {
            if (i.position == item2.position) {
              i.code = item2.code
            }
            i.condition_list.some((ii) => {
              if (ii.position == item2.position) {
                ii.code = item2.code
              }
              return ii.position == item2.position
            })
          })
          customForm_arr.forEach((i) => {
            i.pre_right_data.some((ii) => {
              if (ii.position == item2.position) {
                ii.code = item2.code
              }
              return ii.position == item2.position
            })
            i.operate_right_data.some((ii) => {
              if (ii.position == item2.position) {
                ii.code = item2.code
              }
              return ii.position == item2.position
            })
          })
          console.log(customForm_arr)
          store.commit('set_customForm_right_list', customForm_arr)
          store.commit('set_condition_setup_list', condition_arr)
        }
        // 重复 且 条件and权限中没有对应值可以回填
        // if (item2.code == "") {
        //   item2.code = curr_codeInput_value.value;
        //   codeInput.value.focus();
        // }
      })
    })
  })
}
// 通知左边 更新步骤名称
const change_form_index_name = (e) => {
  EventBus.emit('change_form_index_name', { index: form_index.value, name: e })
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  add_right_form_data.value = {
    name: '',
    right_code: '',
    checked: false,
    id: '',
    right_method: '',
    right_type: 1,
  }
  show_add_right_box.value = false
}
const show_preview_box = ref(false)
const show_preview_type = ref(0)
</script>
<style scope>
.mousedownBox {
  position: absolute;
  left: v-bind('x');
  top: v-bind('y');
  z-index: 101;
  width: 220px;
  border-radius: 3px;
  border: 1px dashed #e6e8eb;
  opacity: 0.7;
  padding: 10px;
}
</style>

<style lang="scss" scoped>
.update_right_list {
  cursor: pointer;
  padding: 5px 10px;
  margin-right: 20px;
  border: 1px solid #ccc;
  &.select {
    color: #3580eb !important;
    border-color: #3580eb !important;
  }
}
.selector_box {
  max-height: 100%;
  flex-shrink: 1;
  overflow: auto;
  white-space: nowrap;
}
:deep(.el-table .cell) {
  display: flex;
  align-items: center;
  justify-content: center;
}
.el-radio-group {
  flex-wrap: nowrap;
}
.base_layout_item_border {
  border: 1px solid #e6e8eb;
}
.select_base_item_index_border {
  border: 1px solid #1ad4af;
}
.base_layout_box {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  width: 100% !important;
  .base_layout_item {
    overflow-y: auto;
    box-sizing: border-box !important;
    display: flex;
    align-items: center;
    justify-content: center;
    &:first-child {
      background-color: #1ad4af;
    }
    &:hover {
      border: 1px solid #3580eb;
    }
  }
}
.container {
  width: 100%;
  height: 100%;
}
.left {
  background-color: #fff;
  width: 300px;
  height: calc(100% - 40px);
  padding: 20px;
  .list_item_box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    margin-top: 10px;
    > div {
      border: 1px solid #ccc;
      padding: 5px 0;
      width: 145px;
      text-align: center;
      margin-bottom: 5px;
      cursor: pointer;
      user-select: none;
    }
    .left_item_select {
      color: #3580eb;
      border: 1px solid #3580eb;
    }
  }
  :deep(.el-collapse-item__header) {
    font-size: 16px;
    font-weight: bold;
  }
}
.right {
  background-color: #fff;
  width: 300px;
  height: calc(100% - 40px);
  padding: 20px;
  > div:last-child {
    height: calc(100% - 32px);
    overflow-y: auto;
  }
  .right_top {
    display: flex;
    align-items: center;
    border-bottom: 1px solid #e6e8eb;
    > div {
      padding: 5px 10px;
      font-size: 16px;
      font-weight: bold;
      cursor: pointer;
    }
    .rightActive {
      color: #3580eb;
    }
  }
}
.main {
  background-color: rgba($color: #fff, $alpha: 0.5);
  width: calc(100% - 720px);
  height: calc(100% - 80px);
  padding: 20px 20px 60px 20px;
  z-index: 102;
  position: relative;
  .delete_area {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: rgba($color: #fff, $alpha: 0.7);
    :deep(.el-input__inner) {
      text-align: center;
    }
  }
  > div {
    height: 100%;
    overflow: auto;
  }
}
</style>
